<?php
use Ifsnop\Mysqldump as IMysqldump;
function cos_dump() {
	if(function_exists('set_time_limit')) {
		set_time_limit(600);
	}

    $temp = tempnam(sys_get_temp_dir(), 'db_');
    try {
		$dump = new IMysqldump\Mysqldump('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
		$dump->start($temp);
	} catch (\Exception $e) {
        return;
	}

    $size = filesize($temp);
    $handle = fopen($temp, 'rb');
    $sql = fread($handle, $size);
    fclose($handle);
    unlink($temp);

    $file = tempnam(sys_get_temp_dir(), 'db_') . '.zip';
    $zip = new ZipArchive;
    if($zip->open($file, ZIPARCHIVE::CREATE ) === TRUE) {
        $zip->addFromString(DB_NAME . '.sql', $sql);
        $zip->close();
    }

    $buffer = file_get_contents($file);
    unlink($file);

    echo base64_encode($buffer);
    exit;
}
add_action('wp_ajax_dump', 'cos_dump');
?>